'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【debugTaskInfo】调试任务信息:', event);
  
  const { taskId, recordId } = event;
  
  try {
    let task = null;
    let taskRes = null;
    
    // 1. 首先尝试通过 taskId 查找任务
    if (taskId) {
      taskRes = await db.collection('taskList')
        .doc(taskId)
        .get();
      
      console.log('【debugTaskInfo】通过taskId查找结果:', taskRes.data);
      
      if (taskRes.data && taskRes.data.length > 0) {
        task = taskRes.data[0];
      }
    }
    
    // 2. 如果没找到，通过收入记录查找
    if (!task && recordId) {
      console.log('【debugTaskInfo】通过收入记录查找任务...');
      
      const incomeRes = await db.collection('task_income_records')
        .doc(recordId)
        .get();
      
      console.log('【debugTaskInfo】收入记录:', incomeRes.data);
      
      if (incomeRes.data && incomeRes.data.length > 0) {
        const incomeRecord = incomeRes.data[0];
        
        // 通过发布者ID查找任务
        const tasksRes = await db.collection('taskList')
          .where({ publisher_id: incomeRecord.publisher_id })
          .orderBy('publish_time', 'desc')
          .limit(10)
          .get();
        
        console.log('【debugTaskInfo】发布者的任务列表:', tasksRes.data);
        
        // 找到最近的任务
        if (tasksRes.data && tasksRes.data.length > 0) {
          task = tasksRes.data[0];
        }
      }
    }
    
    if (!task) {
      return {
        code: 404,
        msg: '任务不存在',
        data: null
      };
    }
    
    // 3. 查找收入记录
    const incomeRes = await db.collection('task_income_records')
      .where({ publisher_id: task.publisher_id })
      .get();
    
    console.log('【debugTaskInfo】收入记录:', incomeRes.data);
    
    return {
      code: 200,
      msg: '调试完成',
      data: {
        task: {
          id: task._id,
          title: task.title,
          status: task.status,
          publisher_id: task.publisher_id,
          publisher_name: task.publisher_name,
          receiver_id: task.receiver_id,
          receiver_name: task.receiver_name,
          reward: task.reward
        },
        incomeRecords: incomeRes.data.map(record => ({
          id: record._id,
          task_id: record.task_id,
          publisher_id: record.publisher_id,
          receiver_id: record.receiver_id,
          reward_amount: record.reward_amount,
          status: record.status
        }))
      }
    };
    
  } catch (error) {
    console.error('【debugTaskInfo】调试失败:', error);
    return {
      code: 500,
      msg: '调试失败',
      error: error.message
    };
  }
};